"""
This script is used to run all the test of openttd performance
"""
import Process,os,time,  sys, math,Analysis, DescriptionParser, ConfigBase,thread
from Configuration import Configuration
from Performance import Performance
import NetworkCommunication
from Util import *
from File import *
import shutil;
Configuration = Configuration()

def expEcho(expName, turn, var):
    output = "turn %d"%turn
    if expName == "1a1" :
        output = output + " AIs %d"%var
    if expName == "1a2":
        output = output + "MapSize %d"%math.pow(2,var)
    if expName == "1a3":
        output = output + "number_towns = number_industries = %d"%var
    if expName == "1a4":
        output = output + "max abillity test"
    if expName == "1c":
        output = output + " server"
    return output

def expEcho2(expName, turn, var):
    output = ""
    if expName == "1a1":
        output = "NumOfAIs " + "%d"%var
    if expName == "1a2":
        output = "MapSize %d"%math.pow(2,var)
    if expName == "1a3":
        output = "number_towns = number_industries = %d"%var
    if expName == "1a4":
        output = "AI = 16, MapSize = 2048 * 2048 "
    if expName == "1c":
        output = " server"
    output = output + " Process.maxYear = %d"%Process.maxYear
    return output

def configAtClient(expName, factor):
    Configuration.initExp(expName) 
    Configuration.expVarChange(expName, factor)

def openTTDInWin32(path):
    os.chdir(path);
    cmd = "\"" + os.path.join(path, "openttd.exe") + "\"" + " -D";
#    cmd = cmd + " -c " + os.path.join(path, "openttd.cfg")
#    cmd = "\"" + cmd + "\"";
    print cmd;
    os.system(cmd);

def startOpenTTDWindows(binaryPath):
    thread.start_new_thread(openTTDInWin32,(binaryPath,))
    time.sleep(5)
    
force = False
ip = "node319.das3.tudelft.nl"
"ft means fault tolerance"
def testSingle(expId, expName, maxYear, factor, path = "nullPath", ft="no"):
    print "--------------------------------------------------------------"
    isFT = True
    if ft != "no":
        isFT = True
    turn = totalTurns = 1
    Process.maxYear = maxYear
    address = ""
    localDesktop = False
    if path == "nullPath":
        Configuration.removeAutoSave()
    else:
        hostname = Configuration.getHostName();
        if(sys.platform.find("linux")>=0 and hostname == Configuration.desktopHostname): 
            Process.path = "/root/.openttd/save/autosave"
            localDesktop = True
        Configuration.removeAutoSave()
#        print "I'm else ", path
    path = Configuration.getPath();
    print "The experiment result will be store in " + path;
    ret = ()
    hostname = Configuration.getHostName()
    if(expName[0:1] == '2' or expName == '5'):
        print hostname, "deciding who I am, a client or a server"
        ret = NetworkCommunication.client()
        print "Network receive ", ret
        if len(ret) == 2:
            address = ret[0]
            if expName[0:1] == '2':
                expName = "3" + expName[1:]
            elif expName[0:1] == '5':
                expName = "6" + expName[1:]
        elif len(ret) == 1 and ret[0] == "server":
            print "I am server"
    if force == True and ip != "" and hostname.find("siqi")>=0:
        expName = "3" + expName[1:]
        address = ip
    print hostname, "now my expName is ", expName
    if os.path.exists(path) == False:
        print path;
        mkdir(path)
    """Profiler """
    measurement = Performance()
    measurement.flag = 1
    measurement.Configuration = Configuration
    print "the path is " + measurement.Configuration.path
    measurement.initVal(expId, expName, factor)
    measurement.start()
    time.sleep(3)
    """For each result file, there are some lines which are configuration parameters(not data to be processed)"""
    Analysis.updateSkipList(Process.maxYear)
    path2 = os.path.join(path, expName)
    print path2
    if(sys.platform.find("win")>=0):
        mkdir(toWinFile(path2));
    else: 
        try:
            os.mkdir(path2);
        except Exception, e:
            pass
    
#    try:
#        if os.path.exists(path2) == False:
#            os.mkdir(path2)
#    except :
#        pass
    filename = Configuration.getExpLog(expId, expName, factor)
    cwd = os.getcwd();
    file = open(filename,"w")
    print filename
    print >>file, 1
    for i in xrange(factor,factor + 1/1):
        starttime = time.time()
        print >> file, "-----------" + time.asctime() + "----------- %d"%expId + "_" + expName + "\n%f"%starttime 
        print >>file , expEcho2(expName, turn, i), " %d"%expId
        file.flush()
        if expName == "1c":
            print ""
#            test1c_server.server(i, expId, turn)
        else:
            configAtClient(expName, factor)
            if(os.path.exists(ConfigBase.getBinaryDirectoryForRunPath())):
                shutil.rmtree(ConfigBase.getBinaryDirectoryForRunPath());
            shutil.copytree(ConfigBase.getBinaryDirectoryPath(), ConfigBase.getBinaryDirectoryForRunPath());
            binaryPath = ConfigBase.getBinaryDirectoryForRunPath()
            Configuration.removeAutoSave();

            if sys.platform == "win32":
                startOpenTTDWindows(ConfigBase.getBinaryDirectoryForRunPath())
                os.chdir(cwd);#return origin directory
            else :
                "if you want to start a game with a visual end, please use -g"
                if(expName[0:1] == '2' or expName == "5"):
                    hostname = Configuration.getHostName()
                    os.system("echo "+ hostname+" > serveraddress.txt")
                if (expName[0:1] == '3' or expName == "6"):
                    addon = ""
                    if expName[0:1] == '3':
                        addon = " -v null" 
                    address = Configuration.appendAddress(address)
                    if localDesktop == True:
                        cmd = "cd /root/1.0.5_modified/bin/; nohup ./openttd -d 1 -x -n "+ address + "&"
                        os.system(cmd)
                    else:
                        for cc in range(0, 1):
                            os.system("cd " + binaryPath + "; nohup ./openttd" + addon + " -n " + address + "&")
                            time.sleep(2)
                elif expName.find("2a7")>=0:
#                    print >> ft, time.time()
#                    ft.flush()
                    os.system("cd " + binaryPath + "; nohup ./openttd -d 1 -x -D&")
                elif expName == "1a7":
                    os.system("cd " + binaryPath + "; nohup ./openttd -d 1 -D&")
                else:
                    if localDesktop == True:
                        cmd = DescriptionParser.getExecuteableCommands(expName,1 )
                    else :
                        cmd = DescriptionParser.getExecuteableCommands(expName,0)
                    print cmd;
                    os.system(cmd)
        Process.killOpenTTD(file, expId, expName, factor, hostname, Configuration.getAutoSavePath(expName), isFT, cwd)
        
        endtime = time.time()
        print >> file,"%f"%endtime + "\n-----------" + time.asctime() + "-----------\n"
        file.flush()
#        if expName == "1c":
##            DB.type = 2
#            test1c_server.copyFile(expId, i)
#        DB.insert(expId, expName, turn, i, starttime, endtime, -1.0, Process.maxYear, filename)
        measurement.flag = 0
        measurement.save()
#        "A sleep ensure there is not multiple thread read/write a same file"
#        time.sleep(5);
        print "after measurement.save()"
#        Analysis.updateSkipList(Process.maxYear)
        Analysis.staticsCPUandMem(expId, expName, 1, totalTurns, factor, factor, Process.maxYear)
#        removeDir(fm(ConfigBase.getBinaryDirectoryForRunPath()));
        print "end of this script--------------------------------------------------------------"
    
if __name__ == "__main__":
    if len(sys.argv) >= 7:
        testSingle(string.atoi(sys.argv[1]), sys.argv[2], string.atoi(sys.argv[3]), string.atoi(sys.argv[4]), sys.argv[5], sys.argv[6])
    elif len(sys.argv) >= 6:
        testSingle(string.atoi(sys.argv[1]), sys.argv[2], string.atoi(sys.argv[3]), string.atoi(sys.argv[4]), sys.argv[5])
    elif len(sys.argv) >= 5:
        testSingle(string.atoi(sys.argv[1]), sys.argv[2], string.atoi(sys.argv[3]), string.atoi(sys.argv[4]))
    else:
        testSingle(10000, "1a1", 1, 1)
    
    #for expName in expNames:
    #    Analysis.staticsCPUandMem(expId, expName, turn)
    ##    Analysis2.plot(expName)
    #    Analysis2.boxplot(expName, 1)
    #    Analysis2.boxplot(expName, 2)
    #    Analysis.generateNetworkReport(measurement.networkFileName)
    #    Analysis.AnalysisNetwork(expName, totalTurns)
    #    Analysis2.plotNetwork(expName)
